package eg.com.iti.common.factory;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import eg.com.iti.common.constant.ExceptionCodes;
import eg.com.iti.common.exception.ITIBusinessException;
import eg.com.iti.common.exception.ITISystemException;
import eg.com.iti.common.service.BaseService;

public class ServiceFactory {
	
	private static Map<String, BaseService> serviceMap = new HashMap<String, BaseService>();  
	public static ResourceBundle resourceBundle = ResourceBundle.getBundle("common.factory.ServiceFactory");
	public static<T extends BaseService> T createService(String serviceName) throws ITISystemException {
		
		if (serviceMap.containsKey(serviceName)) {
			return (T)serviceMap.get(serviceName);
		}
		String baseServiceFullyQualifiedName = resourceBundle.getString(serviceName);
		try {
			BaseService ref = (T)Class.forName(baseServiceFullyQualifiedName).newInstance();
			serviceMap.put(serviceName, ref);
			return (T)ref;
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			throw new ITISystemException(ExceptionCodes.INSTANTIATION_EXCEPTION);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			throw new ITISystemException(ExceptionCodes.ILLEGAL_ACCESS_EXCEPTION);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			throw new ITISystemException(ExceptionCodes.CLASS_NOT_FOUND_EXCEPTION);
		}	
	}
}
